package com.boo.service;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import util.BooPreference;
import util.Constant;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.thuanhoang.boo.HomeActivity;
import com.thuanhoang.boo.UpdateInfoActivity;
import com.thuanhoang.boo.model.ObjUser;
import com.thuanhoang.boo.model.manage.ObjUserMng;

public class AccountService extends BaseService {
	Context context;
	public static final String SENDER_ID = "513754115434";

	public AccountService(Activity parentActivity) {
		super(parentActivity);
		context = (Context) parentActivity;
	}

	public void autoRegister() {
		String userId = new BooPreference(context).getPref()
				.getString(BooPreference.KEY_USER_ID, "").toString();
		String gcm = new BooPreference(context).getPref()
				.getString(BooPreference.KEY_GCM, "").toString();
		if (userId.equals("") || gcm.equals("")) {
			Log.e("user_id", "unknown");
			// deviceToken: GCM id
			new RegisterBackground().execute();
		} else {
			Log.e("user_id", userId);
		}
	}

	public void register(String userName, String phone) {

	}

//	public void updateAccountInfo(String id, String name, String email,
//			String phone, String birthday, boolean isGirl, String address) {
//		String url = Constant.getURLupdateCustomer(id, name, phone, email,
//				birthday, address);
//		Toast.makeText(context, "POST UDPATE USER ACC", Toast.LENGTH_SHORT)
//				.show();
//		ObjUserMng userMng = new ObjUserMng(context);
//		ArrayList<ObjUser> lstUser = userMng.select();
//		if (lstUser == null || lstUser.isEmpty()) {
//			ObjUser user = new ObjUser(-1, new String[ObjUser.NUM_FIELDS]);
//			user.setCustName(name);
//			user.setCustEmail(email);
//			user.setBirthday(birthday);
//			user.setCustAddress(address);
//			user.setCustPhone(phone);
//			user.setGender(isGirl?"female":"male");
//			user.setCustId(id);
//			// ...
//			userMng.insertNewTo(user.getValues());
//		} else {
//			ObjUser user = lstUser.get(0);
//			user.setCustName(name);
//			user.setCustEmail(email);
//			user.setBirthday(birthday);
//			user.setCustAddress(address);
//			user.setCustPhone(phone);
//			user.setGender(isGirl?"female":"male");
//			user.setCustId(id);
//			// ...
//			userMng.edit(user._id, user.getValues());
//		}
//	}

	class RegisterBackground extends AsyncTask<String, String, String> {
		String deviceId, latitude, longitude, deviceToken/* gcm id */,
				appVersion, osVersion;
		GoogleCloudMessaging gcm;
		String regId = "";

		@Override
		protected String doInBackground(String... params) {
			// gcm
			gcm = GoogleCloudMessaging.getInstance(context);
			try {
				regId = gcm.register(SENDER_ID);
				if (regId == null || regId.equals("")) {
					regId = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			// deviceToken: gcm
			deviceToken = regId == null ? "" : regId;
			new BooPreference(context).getPref().edit()
					.putString(BooPreference.KEY_GCM, deviceToken).commit();

			// deviceId
			
			deviceId =  Secure.getString(context.getContentResolver(),Secure.ANDROID_ID);

			// latitude & longitude
			try {
				LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
				Location location = locationManager
						.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				if (location == null) {
					location = locationManager
							.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				}
				if (location==null) {
					Criteria crit = new Criteria();
					crit.setAccuracy(Criteria.ACCURACY_FINE);
					String provider = locationManager.getBestProvider(crit, true);
					location = locationManager.getLastKnownLocation(provider);
				}
				
				latitude = location.getLatitude() + "";
				longitude = location.getLongitude() + "";
			} catch (Exception e) {
				latitude = "";
				longitude = "";
			}

			// app version
			try {
				PackageInfo pInfo = context.getPackageManager().getPackageInfo(
						context.getPackageName(), 0);
				appVersion = pInfo.versionName;
			} catch (NameNotFoundException e) {
				appVersion = "-1";
			}

			// os version
			osVersion = android.os.Build.VERSION.RELEASE+"";

			return null;
		}

		@Override
		protected void onPostExecute(String regId) {
			super.onPostExecute(regId);
			try{
				// send to server
				JSONObject jsonParams = new JSONObject();
				jsonParams.put("deviceId",deviceId );
				jsonParams.put("latitude", latitude);
				jsonParams.put("longitude", longitude);
				jsonParams.put("deviceType", "android");
				jsonParams.put("deviceToken", deviceToken);
				jsonParams.put("AppVersion", appVersion);
				jsonParams.put("OSversion", osVersion);
				StringEntity entity = new StringEntity(jsonParams.toString());

				AccountService.this.post(Constant.API_AUTO_REGIS_URL, entity,new JsonHttpResponseHandler(){	// do not save to database!!
					@Override
					public void onSuccess(JSONObject response) {
						Log.e("autoregister", "autoregister:"+response.toString());
						// save to Preference...
						try {
							JSONObject result = response.getJSONObject("Result");
							String userStr = result.toString();
							Gson gson = new Gson();
							HomeActivity.userInfo = gson.fromJson(userStr, ObjUser.class);
							String custId = result.optString("custId");
							if(!custId.equals(""))
								new BooPreference(context).getPref().edit().putString(BooPreference.KEY_USER_ID, custId).commit();
							Intent i = new Intent(UpdateInfoActivity.USER_UPDATE);
							i.putExtra("userId", response.getString("custId")+"");
							context.sendBroadcast(i);
							return;
						} catch (JSONException e) {
							e.printStackTrace();
						}
						//						AccountService.this.setCache(url, json);
						Intent i = new Intent(UpdateInfoActivity.USER_UPDATE);
						i.putExtra("userId", "");
						context.sendBroadcast(i);
					}

					@Override
					public void onFailure(Throwable error) {
						error.printStackTrace();
						Intent i = new Intent(UpdateInfoActivity.USER_UPDATE);
						i.putExtra("userId", "");
						context.sendBroadcast(i);
					}
				});
			}
			catch (Exception e){

			}
		}
	}
}
